    package model;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.FrameBodyAPIC;
import org.farng.mp3.id3.ID3v2_4;
import org.farng.mp3.id3.ID3v2_4Frame;

/**
 * Mit dieser Klasse kann man aus einer MP3 Datei eine Bilddatei extrahieren<br>
 * rausziehen.
 * 
 * @author Kevin Porebski(20090068)
 * @version 1.0
 * 
 */
public class Load_ID3_Image {

	/**
	 * Diese Methode liest aus der MP3 Datei, falls vorhanden, eine Bilddatei in<br>
	 * Form eines BufferedImage mithilfe der ID3 Tag Java Libary.<br>
	 * (http://javamusictag.sourceforge.net/)
	 * 
	 * @return
	 * @throws Load_ID3_Image_Exception 
	 * @throws TagException 
	 * @throws IOException 
	 */
	public static BufferedImage loadImage(File mp3SourceFile) throws Load_ID3_Image_Exception {
		BufferedImage bi = null;
		
		MP3File mp3file;
		try {
			mp3file = new MP3File(mp3SourceFile);
		} catch (IOException e) {
			throw new Load_ID3_Image_Exception("Konnte nicht \""+mp3SourceFile+"\" lesen");
		} catch (TagException e) {
			throw new Load_ID3_Image_Exception("Fehler beim ID3 Tag lesen der Datei: \""+mp3SourceFile+"\"");
		} catch(UnsupportedOperationException e){
		    throw new Load_ID3_Image_Exception();
		} catch(StringIndexOutOfBoundsException e){
		    throw new Load_ID3_Image_Exception();
		}
		ID3v2_4 id3_23 = new ID3v2_4(mp3file.getID3v2Tag());
		
		Iterator it = id3_23.getFrameIterator();
		Object obj;
		ID3v2_4Frame frame;
		while (it.hasNext()) {
			obj = it.next();
			if (obj != null) {
				frame = (ID3v2_4Frame) obj;
				if(frame.getBody() instanceof FrameBodyAPIC){
					byte[] picByte = (byte[])(((FrameBodyAPIC)frame.getBody()).getObject("Picture Data"));
					if(picByte != null){
						ByteArrayInputStream bais = new ByteArrayInputStream(picByte);
						try{
							bi = ImageIO.read(bais);
							return bi;
						}catch(IOException ioe){
							throw new Load_ID3_Image_Exception("Konnte nicht \""+mp3SourceFile+"\" ID3 Bild lesen");
						}
//						ImageIO.write(bi, "png", new File("C:\\img.png"));
					}
				}					
			}
		}
		
		throw new Load_ID3_Image_Exception("Ende der Methode Fehler");
	}
}
